package main

import (
	"fmt"
	"reflect"
)

// 修改值

func testInt(v interface{}, target int) {

	val := reflect.ValueOf(v)

	// 获取kind
	kind1 := val.Kind()

	if kind1 != reflect.Ptr {
		return
	}

	val.Elem().SetInt(int64(target))
}

func testFloat64(v interface{}) {

	typ := reflect.TypeOf(v)
	fmt.Printf("typ的类型=%T, typ的值=%v\n", typ, typ)

	val := reflect.ValueOf(v)
	fmt.Printf("val的类型=%T, val的值=%v\n", val, val)

	// 获取kind
	kind := val.Kind()
	fmt.Printf("kind的类型=%T, kind的值=%v\n", kind, kind)

	// 获取值
	float := val.Float()
	fmt.Printf("float的类型=%T, float的值=%v\n", float, float)

	// interface
	i := val.Interface()
	f := i.(float64)
	fmt.Printf("f的类型=%T, f的值=%v\n", f, f)
}

type student struct {
	Name string
	Age  int
}

func testStruct(v interface{}, fieldName string, targetValue interface{}) {

	val := reflect.ValueOf(v)

	// 获取kind
	kind1 := val.Kind()

	if kind1 != reflect.Ptr {
		return
	}

	elem := val.Elem()

	if elem.Kind() != reflect.Struct {
		return
	}

	field := elem.FieldByName(fieldName)
	field.Set(reflect.ValueOf(targetValue))
}

func main() {

	i := 1
	testInt(&i, 2)
	fmt.Printf("i=%v, i的地址=%p\n", i, &i)

	stu := student{"admin", 20}
	testStruct(&stu, "Name", "xuguofeng")
	fmt.Printf("stu=%v\n", stu)

	fmt.Println("---")

	testFloat64(0.9)
}
